package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ccj.poptabview.FilterConfig;
import com.ccj.poptabview.PopTabView;
import com.ccj.poptabview.base.BaseFilterTabBean;
import com.ccj.poptabview.bean.FilterGroup;
import com.ccj.poptabview.bean.FilterTabBean;
import com.ccj.poptabview.listener.OnPopTabSetListener;
import com.ccj.poptabview.loader.PopEntityLoaderImp;
import com.ccj.poptabview.loader.ResultLoaderImp;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessActivity;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ActivityListVO;
import com.digitalchina.lxnsy.entity.ActivityTypeVO;
import com.digitalchina.lxnsy.entity.ShareFarmTypeVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ActivityListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/7/17 10:50
 * 修改备注：
 * ================================================
 */
public class ActivityListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener,OnPopTabSetListener {

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.tv_search)
    EditText tvSearch;
    @Bind(R.id.iv_cancel)
    ImageView ivCancel;
    @Bind(R.id.expand_pop)
    PopTabView expandPop;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private String keyWord = ""; // 关键字
    private String typeCode = ""; // 活动类型(typeCode为1时查询首页活动)
    private String activityState = ""; // 活动状态 （汉字格式：即将开始，正在进行，已结束）

    private List<ActivityListVO> voList = new ArrayList<>();
    private List<ActivityTypeVO> typeList = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_activity_list);
        setTitle("活动列表");
    }

    @Override
    public void initMember() {

        // 活动类型
        BusinessActivity.getActivityType(this, mHandler);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(this, 1, 0, 0));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ActivityListHolder(parent);
            }
        });

        onRefresh();

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });


        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                GotoUtil.gotoActivity(ActivityListActivity.this, ActivityDetailActivity.class, "ActivityVO", adapter.getAllData().get(position));
            }
        });

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keyWord = "";
                tvSearch.setText("");
                onRefresh();
            }
        });

        tvSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    // 刷新列表数据
                    if (!keyWord.equals(tvSearch.getText().toString())) {
                        keyWord = tvSearch.getText().toString();
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_SEARCH_ACTIVITY_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_SEARCH_ACTIVITY_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_GET_ACTIVITY_TYPE_SUCCESS: // 活动类型
                        setActivityType(msg.obj.toString());
                        break;
                }
            }
        };
    }

    // 设置活动类型
    private void setActivityType(String json) {

        typeList = FastJsonUtil.getListBeanRow(json, "options", ActivityTypeVO.class);
        if (typeList != null && typeList.size() > 0) {

            ActivityTypeVO vo = new ActivityTypeVO();
            vo.setLabel("全部");
            vo.setValue("");
            typeList.add(0,vo);

            FilterGroup filterGroup1 = getMyData1();
            FilterGroup filterGroup2 = getMyData2();

            expandPop.setOnPopTabSetListener(this)
                    .setPopEntityLoader(new PopEntityLoaderImp()).setResultLoader(new ResultLoaderImp()); //配置 {筛选类型}  方式
            expandPop.addFilterItem(filterGroup1.getTab_group_name(), filterGroup1.getFilter_tab(), filterGroup1.getTab_group_type(), filterGroup1.getSingle_or_mutiply());
            expandPop.addFilterItem(filterGroup2.getTab_group_name(), filterGroup2.getFilter_tab(), filterGroup2.getTab_group_type(), filterGroup2.getSingle_or_mutiply());

        }
    }

    /**
     * 设置第一组筛选器
     *
     * @return
     */
    public FilterGroup getMyData1() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("活动类型");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        for (int i = 0; i < typeList.size(); i++) {

            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(typeList.get(i).getValue());
            singleFilterBean.setTab_name(typeList.get(i).getLabel());
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    /**
     * 设置第二组筛选器
     *
     * @return
     */
    public FilterGroup getMyData2() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("活动状态");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        String array[] =
                {"全部", "即将开始", "正在进行", "已结束"};
        String array1[] =
                {"", "0", "1", "2"};
        for (int i = 0; i < array1.length; i++) {

            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(array1[i]);
            singleFilterBean.setTab_name(array[i]);
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBeanRow(object.toString(), "rows", ActivityListVO.class);

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);


        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessActivity.searchActivity(this, keyWord, typeCode, activityState, page, limit, "1",mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessActivity.searchActivity(this, keyWord, typeCode, activityState, page, limit,"1", mHandler);
        }
    }

    @Override
    public void onPopTabSet(int index, String label, Object params, String value) {
        switch (index) {
            case 0:
                typeCode = params +"";
                break;
            case 1:
                activityState = params +"";
                break;
        }

        onRefresh();
    }

}
